package com.tanhua.mongo.api;

import com.tanhua.api.UserLikeApi;
import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.net.URLPermission;


@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存喜欢/不喜欢数据

    @Override
    public boolean save(Long userId, Long likeUserId, boolean isLike) {
        try {
            //封装查询条件
            Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
            //判断数据是否存在
            if(mongoTemplate.exists(query, UserLike.class)){
                //存在 修改
                Update update = Update.update("isLike",isLike);
                mongoTemplate.updateFirst(query,update,UserLike.class);
            }else{
                //不存在  新增
                UserLike userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setIsLike(isLike);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setUpdated(System.currentTimeMillis());
                mongoTemplate.save(userLike);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
